import React, { useState, useRef, useEffect } from 'react';
import { View, StyleSheet, TextInput, TouchableOpacity, Text, Image, ActivityIndicator, Alert, Platform } from 'react-native';
import { Ionicons } from '@expo/vector-icons';
import * as ImagePicker from 'expo-image-picker'; 
import axios from 'axios';
import { NativeStackScreenProps } from '@react-navigation/native-stack';

// Import Camera
import { Camera as ExpoCamera } from 'expo-camera';

// 定义路由参数类型
type RootStackParamList = {
  Camera: {
    imageUri?: string;
  };
};

type CameraScreenProps = NativeStackScreenProps<RootStackParamList, 'Camera'>;

export default function CameraScreen({ navigation, route }: CameraScreenProps) {
  const [hasPermission, setHasPermission] = useState(null);
  const [extractedText, setExtractedText] = useState('');
  const [processing, setProcessing] = useState(false);
  const [capturedImage, setCapturedImage] = useState(null);
  
  // 处理从主页传递的图片
  useEffect(() => {
    if (route.params?.imageUri) {
      processImage(route.params.imageUri).catch((error: Error) => {
        console.error("处理传递的图片时出错:", error);
        Alert.alert("错误", "处理图片时出现问题");
      });
    }
  }, [route.params?.imageUri]);
  
  // 请求相机权限
  useEffect(() => {
    (async () => {
      try {
        if (ExpoCamera) {
          const { status } = await ExpoCamera.requestCameraPermissionsAsync();
          setHasPermission(status === 'granted');
        } else {
          setHasPermission(false);
          console.warn("相机组件不可用");
        }
      } catch (err) {
        console.error('初始化相机时出错:', err);
        setHasPermission(false);
      }
    })();
  }, []);
  
  // 处理图片文字识别
  const processImage = async (imageUri: string): Promise<void> => {
    if (!imageUri) return;
    
    setCapturedImage(imageUri);
    setProcessing(true);
    
    try {
      let res = await axios.post('http://192.168.1.45:3000/ycf/TextRecognition', { image: imageUri });
      if (res.data.code === 200) {
        if (res.data.data) {
          setExtractedText(res.data.data);
        } else {
          Alert.alert("提示", "未能识别出文字");
        }
      } else {
        Alert.alert("错误", res.data.message || "识别失败");
      }
    } catch (error) {
      console.error("识别文字时出错:", error);
      Alert.alert("错误", "识别文字时出现问题，请检查网络连接");
    } finally {
      setProcessing(false);
    }
  };
  
  // 处理相机拍照
  const handleCamera = async (): Promise<void> => {
    const { status } = await ImagePicker.requestCameraPermissionsAsync();
    if (status !== 'granted') {
      alert('需要相机权限才能拍照！');
      return;
    }

    try {
      const result = await ImagePicker.launchCameraAsync({
        allowsEditing: true,
        quality: 0.7,
        base64: true,
      });

      if (!result.canceled) {
        console.log("拍照成功，准备识别文字");
        setCapturedImage(result.assets[0].uri);
        setProcessing(true);
        
        try {
          if (!result.assets[0].base64) {
            console.error("获取图片base64失败");
            setProcessing(false);
            Alert.alert("错误", "获取图片数据失败，请重试");
            return;
          }
          
          const base64Image = `data:image/jpeg;base64,${result.assets[0].base64}`;
          
          const response = await axios.post('http://192.168.1.45:3000/ycf/TextRecognition', { 
            image: base64Image
          }, {
            timeout: 30000,
            headers: {
              'Content-Type': 'application/json'
            }
          });
          
          if (response.data.code === 200) {
            if (response.data.data) {
              setExtractedText(response.data.data);
              Alert.alert("成功", "文字识别成功");
            } else {
              Alert.alert("提示", "未能识别出文字");
            }
          } else {
            Alert.alert("错误", response.data.message || "识别失败");
          }
        } catch (error) {
          console.error("识别文字时出错:", error);
          Alert.alert("错误", "识别文字时出现问题，请检查网络连接");
        } finally {
          setProcessing(false);
        }
      }
    } catch (error) {
      console.error("拍照时出错:", error);
      Alert.alert("错误", "拍照时出现问题");
    }
  };
  
  return (
    <View style={styles.container}>
      {/* 顶部搜索栏 */}
      <View style={styles.header}>
        <TouchableOpacity onPress={() => navigation.goBack()}>
          <View style={styles.backIcon}>
            <Ionicons name="arrow-back" size={24} color="#333" />
          </View>
        </TouchableOpacity>
        <View style={styles.searchBar}>
          <Ionicons name="search-outline" size={20} color="#999" />
          <TextInput 
            style={styles.searchInput}
            placeholder="题目、题号、真题名称"
            placeholderTextColor="#999"
            value={extractedText}
            onChangeText={setExtractedText}
          />
        </View>
        <View style={styles.icon}>
          <Ionicons name="person-outline" size={20} color="#999" />
        </View>
        <View style={styles.icon}>
          <Ionicons name="chatbubble-outline" size={20} color="#999" />
        </View>
      </View>

      {/* 相机按钮 */}
      <View style={styles.cameraButtonContainer}>
        <TouchableOpacity style={styles.cameraButton} onPress={handleCamera}>
          <Ionicons name="camera" size={30} color="white" />
          <Text style={styles.cameraButtonText}>拍照识别</Text>
        </TouchableOpacity>
      </View>

      {processing && (
        <View style={styles.loadingOverlay}>
          <ActivityIndicator size="large" color="#fff" />
          <Text style={styles.loadingText}>正在识别文字...</Text>
        </View>
      )}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#f5f5f5',
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
    paddingVertical: 10,
    paddingTop: Platform.OS === 'ios' ? 50 : 30,
    backgroundColor: 'white',
  },
  cameraContainer: {
    flex: 1,
  },
  camera: {
    flex: 1,
  },
  cameraPlaceholder: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#2c3e50',
  },
  searchBar: {
    flex: 1,
    backgroundColor: '#f0f0f0',
    borderRadius: 20,
    padding: 10,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 15,
    marginRight: 15,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    marginLeft: 10,
  },
  backIcon: {
    marginRight: 10,
  },
  icon: {
    marginLeft: 10,
  },
  cameraControls: {
    position: 'absolute',
    bottom: 30,
    flexDirection: 'row',
    width: '100%',
    justifyContent: 'center',
    alignItems: 'center',
  },
  captureButton: {
    backgroundColor: 'rgba(0,0,0,0.6)',
    padding: 15,
    borderRadius: 50,
    marginHorizontal: 20,
    alignItems: 'center',
  },
  galleryButton: {
    backgroundColor: 'rgba(0,0,0,0.6)',
    padding: 15,
    borderRadius: 50,
    marginHorizontal: 20,
    alignItems: 'center',
  },
  cameraButtonContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1E90FF',
    margin: 15,
    borderRadius: 15,
  },
  cameraButton: {
    alignItems: 'center',
  },
  cameraButtonText: {
    color: 'white',
    fontSize: 16,
    marginTop: 5,
  },
  loadingOverlay: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'rgba(0,0,0,0.5)',
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    color: 'white',
    marginTop: 10,
    fontSize: 16,
  },
}); 